package com.lemon.cloud.gray.feign;

import cn.hutool.core.util.StrUtil;
import com.lemon.cloud.comm.constants.GrayConstant;
import com.lemon.cloud.core.utils.WebUtils;
import com.lemon.cloud.gray.support.GrayFlagContextHolder;
import com.lemon.cloud.gray.util.GrayUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional;

@Slf4j
public class GrayFeignRequestInterceptor implements RequestInterceptor {

    /**
     * 灰度流量请求头标记
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        Optional<HttpServletRequest> optional = WebUtils.getRequest();
        String reqGrayFlag = optional.isPresent() ? optional.get().getHeader(GrayConstant.GRAY_FLAG)
                : GrayFlagContextHolder.getGrayFlag();
        if (StrUtil.isEmpty(reqGrayFlag)){
            //走到灰度节点时，标记当前请求为灰度流量
            reqGrayFlag = GrayUtil.getGrayFlag();
        }
        if (StrUtil.isNotBlank(reqGrayFlag)) {
            log.debug("feign gray add header flag :{}", reqGrayFlag);
            template.header(GrayConstant.GRAY_FLAG, reqGrayFlag);
            GrayFlagContextHolder.setGrayFlag(reqGrayFlag);
        }
    }

}
